package com.mical.demo.controller;


import com.mical.demo.dto.LoginRequest;
import com.mical.demo.dto.LoginResponse;
import com.mical.demo.model.User;
import com.mical.demo.security.JwtTokenUtil;
import com.mical.demo.service.AuthService;
import com.mical.demo.service.TokenStoreService;
import jakarta.servlet.HttpConstraintElement;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Date;

/**
 * 首页控制器
 * @author pan_junbiao
 **/
@RestController
@RequestMapping("/api/auth")
public class IndexController
{
    private final AuthService authService;
    private final JwtTokenUtil jwtTokenUtil;
    private final TokenStoreService tokenStoreService;
    public IndexController(AuthService authService, JwtTokenUtil jwtTokenUtil, TokenStoreService tokenStoreService) {
        this.authService = authService;
        this.jwtTokenUtil = jwtTokenUtil;

        this.tokenStoreService = tokenStoreService;
    }


@PreAuthorize("hasAuthority('USER')")
    @RequestMapping("/index")
    public String index(HttpServletRequest request)
    {
        //获取当前登录人
        String userName = "未登录";
        Principal principal = request.getUserPrincipal();
        if (principal != null)
        {
            userName = principal.getName();
        }

        //返回页面
        request.setAttribute("userName", userName);
        return "/index";
    }
    // Standard header extraction
    private String extractTokenFromHeader(HttpServletRequest request) {
        String header = request.getHeader("Authorization");

        if (header != null && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }

    @PostMapping("/login")
    public  ResponseEntity<LoginResponse>  myLogin(@RequestBody  LoginRequest loginRequest){
       LoginResponse response =authService.authenticateUser(loginRequest);

        String token = response.getToken();
        if (token != null)
           tokenStoreService.storeToken(response.getUsername(), token);

       return   ResponseEntity.ok(response);
    }

    @RequestMapping("/logout")
    public ResponseEntity logout(HttpServletRequest request){
        String token = extractTokenFromHeader(request);
        String username=jwtTokenUtil.getUsernameFromToken(token);
        jwtTokenUtil.invalidateToken(token);
        tokenStoreService.clearAllTokens(username);
         request.getSession().invalidate();

        return ResponseEntity.ok().build();

    }
}